package cn.cloud.project.consumer.config;

import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.nacos.api.config.ConfigChangeEvent;
import com.alibaba.nacos.api.config.ConfigChangeItem;
import com.alibaba.nacos.client.config.listener.impl.AbstractConfigChangeListener;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Configuration;

import java.util.Collection;

/**
 * @author: cql
 * @date: 2024/11/3
 * @description:
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
public class ConfigChangeListener implements InitializingBean {

    private final NacosConfigManager nacosConfigManager;

    @Override
    public void afterPropertiesSet() throws Exception {
        AbstractConfigChangeListener listener = new AbstractConfigChangeListener() {
            @Override
            public void receiveConfigChange(ConfigChangeEvent event) {
                Collection<ConfigChangeItem> changeItems = event.getChangeItems();
                log.info("ConfigChangeItem: {}", changeItems.toString());
            }
        };

        this.nacosConfigManager.getConfigService().addListener("demo-consumer.yaml", "DEFAULT_GROUP", listener);
    }
}